﻿using Future.Web.Utility;
using NLog;
using SqlSugar;
using System.Text;

namespace Future.Web.Extensions
{
    /// <summary>
    /// Sqlsugar扩展
    /// </summary>
    public static class SqlsugarExtension
    {
        /// <summary>
        /// 注册Sqlsugar上下文
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        public static void AddSqlsugarService(this IServiceCollection services, IConfiguration configuration)
        {
            DbType dbType = DbType.SqlServer;

            List<SlaveConnectionConfig> slavaConFig = new();
            List<string> readCon = new();
            configuration.Bind("DbConn:ReadUrl", readCon);
            readCon.ForEach(s =>
            {
                slavaConFig.Add(new SlaveConnectionConfig() { ConnectionString = s });
            });

            string writeCon = configuration.GetSection("DbConn:WriteUrl").Get<string>();
            ConnectionConfig connectionConfig = new()
            {
                //准备添加分表分库
                DbType = dbType,
                ConnectionString = writeCon,
                IsAutoCloseConnection = true,
                MoreSettings = new ConnMoreSettings()
                {
                    DisableNvarchar = true
                },
                SlaveConnectionConfigs = slavaConFig,
            };

            //Sqlsugar aop配置
            static void configAction(SqlSugarClient db)
            {
                db.Aop.DataExecuting = (oldValue, entityInfo) =>
                {
                    if (entityInfo.OperationType == DataFilterType.InsertByObject)
                    {
                        if (entityInfo.PropertyName == "CreateBy")
                        {
                            string userName = GetUserName();
                            entityInfo.SetValue(userName);
                        }
                        if (entityInfo.PropertyName == "CreateTime")
                        {
                            entityInfo.SetValue(DateTime.Now);
                        }
                    }

                    if (entityInfo.OperationType == DataFilterType.UpdateByObject)
                    {
                        if (entityInfo.PropertyName == "UpdateTime")
                        {
                            entityInfo.SetValue(DateTime.Now);
                        }
                        if (entityInfo.PropertyName == "UpdateBy")
                        {
                            string userName = GetUserName();
                            entityInfo.SetValue(userName);
                        }
                    }
                };
                db.Aop.OnLogExecuting = (sql, parameters) =>
                {
                    Logger logger = LogManager.GetCurrentClassLogger();
                    StringBuilder sb = new();
                    sb.Append("执行SQL:" + sql.ToString());
                    foreach (SugarParameter parameter in parameters)
                    {
                        sb.Append($"\r\n参数:{parameter.ParameterName},参数值:{parameter.Value}");
                    }
                    logger.Debug(sb.ToString());
                };
            }

            SqlSugarScope sqlSugar = new(connectionConfig, configAction);

            //这边是SqlSugarScope用AddSingleton
            services.AddSingleton<ISqlSugarClient>(sqlSugar);
        }

        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <returns></returns>
        static string GetUserName()
        {
            string userName = string.Empty;
            var httpcontext = GlobalContext.ServiceProvider.GetService<IHttpContextAccessor>()?.HttpContext;
            if (httpcontext is not null)
            {
                userName = httpcontext.GetUserName();

            }
            return userName;
        }
    }
}
